<template>
  <div class="tab-category px-4 gap-col-16">
    <TagSwiper v-model="tab" :items="categories" item-value="id" item-label="name" @click="onCategoryClick"></TagSwiper>
    <Loading v-if="isLoading"></Loading>
    <div v-else-if="collection.length > 0">
      <div v-for="(item, index) in collection" :key="`category-${index}`">
        <div class="font-size-15 font-weight-400 line-height-125">{{ item?.cate?.name }}</div>
        <div class="card-container">
          <div v-for="(tag, index) in item?.tags" :key="`category-tag-${index}`">
            <TagCard class="pointer" :item="tag" @click="() => onTagClick(tag.keyword)"></TagCard>
          </div>
        </div>
      </div>
    </div>
    <ErrorNodata v-else :style="{ height: '90%' }"></ErrorNodata>
  </div>
  <Jsonld :schema="schema"></Jsonld>
</template>
<script setup>
import { computed, onActivated, onMounted, ref, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSearchStore } from '@/store/search'
import TagCard from '@/components/cards/TagCard.vue'
import ErrorNodata from '@/components/common/ErrorNodata.vue'
import Jsonld from '@/components/common/Jsonld.vue'
import Loading from '@/components/common/Loading.vue'
import TagSwiper from '@/components/common/TagSwiper.vue'
import { useNavRefresh } from '@/compositions/nav/refresh'
import { INTERESTED_IN_MAP, NAVS } from '@/constant'
import API from '@/http'

const searchStore = useSearchStore()
const { updateViewerRouterOriginPath, toTagListViewer } = searchStore

const categories = ref([])
const collection = ref([])
const tab = ref(0)
const isLoading = ref(true)

const route = useRoute()
const router = useRouter()
const prefer = route.params?.prefer

// 嘗試取得當前分類的性向興趣
const currentInterested = computed(() => {
  const _currentCatename = categories.value.find((item) => item.id === tab.value).name.toLowerCase()
  const mapping = { interest: INTERESTED_IN_MAP[_currentCatename], catename: _currentCatename }
  return mapping || null
})

async function fetchCategories() {
  const response = await API.Search.cateTop()
  categories.value = response
  const cate = categories.value.find((item) => item.key === prefer) || response[0]
  tab.value = cate.id
  setPreferPath(cate.key)
}
async function fetchCollection(cate_id) {
  isLoading.value = true
  const response = fetchCollection.cache[cate_id] || (await API.Search.cate({ data: { cate_id } }))
  collection.value = response
  fetchCollection.cache[cate_id] = response
  isLoading.value = false

  updateSchema()
}
async function refresh() {
  fetchCollection.cache = {}
  await fetchCategories()
  await fetchCollection(tab.value)
}

onMounted(refresh)

// 還原 prefer 路徑
onActivated(() => {
  // 必須先讓 SearchMain 完成 updateViewerRouterOriginPath，不然路徑會錯亂
  requestAnimationFrame(() => {
    const cate = categories.value.find((c) => c.id === tab.value)
    if (cate) {
      setPreferPath(cate.key)
    }
  })
})

function onTagClick(keyword) {
  if (currentInterested.value) toTagListViewer(keyword, currentInterested.value)
  else toTagListViewer(keyword)
}

async function onCategoryClick(item) {
  setPreferPath(item.key)
  tab.value = item.id
  await fetchCollection(item.id)
}

function setPreferPath(prefer) {
  router.replace({ params: { prefer } }).then(updateViewerRouterOriginPath)
}

useNavRefresh(NAVS.SEARCH, refresh)

// Jsonld 佈置
const schema = shallowRef(null)
function updateSchema() {
  const cate = categories.value.find((c) => c.id === tab.value)
  const coll = collection.value

  if (!cate) return

  const itemListElement = coll.map((v, i) => ({
    '@type': 'ItemList',
    position: i + 1,
    name: v.cate.name,
    itemListElement: v.tags.map((t, j) => ({
      '@type': 'Thing',
      position: j + 1,
      name: t.keyword,
      url: `https://www.fantasi.one/tag/${t.keyword}`,
    })),
  }))

  schema.value = {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name: `${cate.name} category list`,
    itemListOrder: 'http://schema.org/ItemListOrderAscending',
    itemListElement,
  }
}
onActivated(updateSchema)
</script>
<style scoped lang="scss">
.tab-category {
  height: 100%;
  overflow: auto;
  padding-bottom: 4.5rem;

  .card-container {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}
</style>
